<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class roles extends MY_Controller {
    
    public function __construct()
    {
        parent::__construct();
        $this->lang->load('role');
        //$this->load->model('menu_model');
    }
    
    public function index()
    {
        $this->load->model('roles_model');
        if( !has_permission('System.Role.PageView') ){
            redirect('no_access');
        }
        $this->template->set_page_title( lang('per_title_roles') );
        $this->template->set_view('roles/content_home');
        
        $this->template->render();
    }
    
    public function datatable_roles(){
        $this->load->model('roles_model');
        $aaData = $this->roles_model->load_datatable_roles($_GET,1);
        $totalData = $this->roles_model->load_datatable_roles($_GET,2);
        
        $output = array(
            "sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $aaData['total'],
            "iTotalDisplayRecords" => $totalData['total'],//$iFilteredTotal,
            "aaData" => $aaData['aaData']
        );
    
        echo json_encode( $output );
    }
    
    public function ajax_loadfrm_roles($id = null){
        $this->load->model('roles_model');
        $data = array();
        
        if($id != null){
            $data['role'] = $this->roles_model->getRoleById($id);
            $data['active'] = site_url('roles/edit');
        }else{
            $data['active'] = site_url('roles/add');
            $data['act'] = 'add';
        }
        
        $this->load->view($this->template->template.'/roles/form_add_role',$data);
    }
    
    public function add(){
        $this->load->model('roles_model');
        if( !has_permission('System.Role.Create') ){
            $data = array(
                'flag' => false,
                'error' => array('message' => 'No accsess!','name' => 'error')
            );
            echo json_encode($data);
            exit;
        }
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $role_name = trim( $this->input->post('role_name') );
            $description = $this->input->post('description');
            $candelete = $this->input->post('candelete');
            
            $flag = true;
            $id = 0;
            $error = array();
            
            if( $role_name == '' ){
                $flag = false;
                $error[] = array(
                    'message' => lang('role_error_01'),
                    'name' => 'role_name'
                );
            }else{
                if( $this->roles_model->unique_role($role_name) == false ){
                    $flag = false;
                    $error[] = array(
                        'message' => lang('role_error_02'),
                        'name' => 'role_name'
                    );
                }
            }
            
            if($flag == true){
                $data_insert = array(
                    'role_name' => $role_name,
                    'description' => $description,
                    'default' => 0,
                    'can_delete' => $candelete,
                    'deleted' => 0
                );
                
                $id = $this->roles_model->insertRole($data_insert);
            }
            
            $data = array(
                'flag' => $flag,
                'error' => $error,
                'id' => $id,
                'name' => $role_name,
                'description' => $description
            );
            echo json_encode($data);
            
        }
    }
    public function edit(){
        $this->load->model('roles_model');
        if( !has_permission('System.Role.Update') ){
            $data = array(
                'flag' => false,
                'error' => array('message' => 'No accsess!','name' => 'error')
            );
            echo json_encode($data);
            exit;
        }
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $role_id = $this->input->post('role_id');
            $role_name = trim( $this->input->post('role_name') );
            $description = $this->input->post('description');
            $candelete = $this->input->post('candelete');
            
            $flag = true;
            $error = array();
            
            if( $role_name == '' ){
                $flag = false;
                $error[] = array(
                    'message' => lang('role_error_01'),
                    'name' => 'role_name'
                );
            }else{
                if( $this->roles_model->unique_role_edit($role_id,$role_name) == false ){
                    $flag = false;
                    $error[] = array(
                        'message' => lang('role_error_02'),
                        'name' => 'role_name'
                    );
                }
            }
            
            if($flag == true){
                $data_update = array(
                    'role_name' => $role_name,
                    'description' => $description,
                    'can_delete' => $candelete
                );
                
                $this->roles_model->updateRole($data_update,$role_id);
            }
            $role = $this->roles_model->getRoleById($role_id);
            $html = '';
            if($role['default'] == 0){
                $html = '<img src="'.base_url('template/ess/images/publish_x.png').'" alt="">';
            }elseif($role['default'] == 1){
                $html = '<img src="'.base_url('template/ess/images/tick.png').'" alt="">';
            }
            
            $data = array(
                'flag' => $flag,
                'error' => $error,
                'id' => $role_id,
                'name' => $role['role_name'],
                'description' => $role['description'],
                'default' => $html
            );
            echo json_encode($data);
            
        }
    }
    public function delete(){
        $this->load->model('roles_model');
        if( !has_permission('System.Role.Delete') ){
            $data = array(
                'flag' => false,
                'error' => array('message' => 'No accsess!','name' => 'error')
            );
            echo json_encode($data);
            exit;
        }
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $role_id = $this->input->post('id');
            $flag = true;
            $message = '';
            $role = $this->roles_model->getRoleById($role_id);
            
            if($role['can_delete'] == 1){
                $flag = false;
                $message = lang('role_msg_02');
            }else{
                $data_update = array('deleted' => 1);
                $this->roles_model->updateRole($data_update,$role_id);
                $message = lang('role_msg_01');
            }
            
            $data = array(
                'flag' => $flag,
                'message' => $message,
            );
            echo json_encode($data);
        }
    }
    
    public function permission(){
        $this->load->model('roles_model');
        if( !has_permission('System.Role.Settings') ){
            redirect('no_access');
        }
        $roles = $this->roles_model->getRoleActive();
        $this->template->set('roles',$roles);
        $this->template->set_page_title( lang('per_title_roles') );
        $this->template->set_view('roles/content_permission');
        
        $this->template->render();
    }
    
    public function role_permission(){
        $this->load->model('roles_model');
        if( !has_permission('System.Role.Settings') ){
            echo lang('msg_noaccess');
            exit;
        }
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $role_id = $this->input->post('id');
            $role = $this->roles_model->getRoleById($role_id);
            //xu ly datatable permission
            $data_active = $this->roles_model->getAllPermissionByRoleId($role_id);
            
            $list_permission_active = array();
            if($data_active){
                foreach($data_active As $item){
                    $list_permission_active[] = $item->permission_id;
                }
            }
        
            $data = $this->roles_model->loadPermission();
            //var_dump($data);
            $table_data = array();
            
            foreach($data As $key=>$item){
                $col_header = array();
                $row_item = array();
                $i = 0;
                
                $row_item['0header0'][$i] = '';
                foreach($item As $row){
                    $row_item[$row['row']][$row['col']] = array('permission_id' => $row['permission_id'],'description'=>$row['description'],'checked' => ( in_array($row['permission_id'],$list_permission_active) ) ? true :false 
                        );
                    if( !in_array($row['col'],$row_item['0header0']) ){
                        $row_item['0header0'][$i++] = $row['col'];
                    }
                    
                }
                //$row_item[$key][] = $col_header;
                $table_data[$key] = $row_item;
            }
            
            $this->load->view($this->template->template.'/roles/table_permission',array('table_data'=>$table_data,'role'=>$role,'roleId'=>$role_id));
            
        }
        
    }
    
    function setPermission($roleId, $permissionId, $status){
        $this->load->model('roles_model');
        if( !has_permission('System.Role.Settings') ){
            echo '...';
            exit;
        }
        //echo $status;
        switch($status){
            case 'set':
                $data_insert = array('role_id'=>$roleId,'permission_id'=>$permissionId);
                $this->roles_model->insertRolePermission($data_insert);
            break;
            
            case 'unset':
                $this->roles_model->deleteRolePermission($roleId, $permissionId);
            break;
        }
        
        $this->load->view($this->template->template.'/roles/ajax_change_permission',array('role_id'=>$roleId,'permission_id'=>$permissionId,'status'=>$status));
    }
    
    /*
    function list_permission($page = 1)
    {
        $this->load->model('roles_model');
        
        $itemsPerPage=20;
        $space=5;
        if($page == 0){$page=1;}
        
        
        $start = ($page - 1) * $itemsPerPage;
        $items = $this->roles_model->getAllListPermission($itemsPerPage,$start);
        $totalItems = $this->roles_model->countAllListPermission();
        $totalPages = round($totalItems / $itemsPerPage);
        
        if( $totalItems%$itemsPerPage != 0 ){
            $totalPages = ($totalItems - ( $totalItems%$itemsPerPage ) ) /$itemsPerPage + 1;
        }
        
        $this->load->view('default/permission/ajax_list_permission',array(
            'items'=> $items,
            'itemsPerPage'=>$itemsPerPage,
            'page'=>$page,
            'totalPages'=>$totalPages,
            'space' => $space
        ));
    }
    
    function insert(){
        $this->load->model('roles_model');
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $this->form_validation->set_rules('name', 'Permission Name', 'required|min_length[3]|max_length[100]|');
            $this->form_validation->set_rules('description', 'Description', 'required|max_length[255]|');
            
            if ($this->form_validation->run() == FALSE){
                $this->form_validation->set_error_delimiters('<div class="status error">
    <p class="closestatus"><a href="" title="Close">x</a></p><p><img SRC="img/icons/icon_error.png" alt="Error" /><span>Error!</span>', '</p></div>');

            }else{

                $name = $this->input->post('name');
                $description = $this->input->post('description');
                $active = $this->input->post('active');
                
                $insertdata = array(
                    'name' => $name,
                    'description' => $description,
                    'status' => $active
                );
                $new_permissionId = $this->roles_model->insertPermission($insertdata);
                
                redirect('permission', 'location', 301);
            }
        }
        
        $this->template->parse_view('sidebarleft','default/sidebarleft/sidebarleft',array('menu' => 'permission'));
        $this->template->parse_view('content', 'default/permission/insert_permission', array(
            'action' => site_url('permission/insert'),
            'page_type' => 'insert'
        ));
       // Render template
        $this->template->render();
        
    }
    
    function edit($permissionId = 0){
        $this->load->model('roles_model');
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        $permission = $this->roles_model->getPermissionById($permissionId);
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $this->form_validation->set_rules('name', 'Role Name', 'required|min_length[3]|max_length[100]|');
            $this->form_validation->set_rules('description', 'Description', 'required|max_length[255]|');
            
            if ($this->form_validation->run() == FALSE){
                $this->form_validation->set_error_delimiters('<div class="status error">
    <p class="closestatus"><a href="" title="Close">x</a></p><p><img SRC="img/icons/icon_error.png" alt="Error" /><span>Error!</span>', '</p></div>');
                
            }else{
                $name = $this->input->post('name');
                $description = $this->input->post('description');
                $active = $this->input->post('active');
                
                $updatetdata = array(
                    'name' => $name,
                    'description' => $description,
                    'status' => $active
                );
                $this->roles_model->updatePermission($permissionId,$updatetdata);
                
                redirect('permission', 'location', 301);
            }
        }
        
        $this->template->parse_view('sidebarleft','default/sidebarleft/sidebarleft',array('menu' => 'roles'));
        $this->template->parse_view('content', 'default/permission/insert_permission', array(
            'action' => site_url('permission/edit/'.$permissionId),
            'page_type' => 'edit',
            'permission'=>$permission
        ));
       // Render template
        $this->template->render(); 
    }

    function setPermission($roleId, $permissionId, $status){
        $this->load->model('roles_model');
        //echo $status;
        switch($status){
            case 'set':
                $data_insert = array('role_id'=>$roleId,'permission_id'=>$permissionId);
                $this->roles_model->insertRolePermission($data_insert);
            break;
            
            case 'unset':
                $this->roles_model->deleteRolePermission($roleId, $permissionId);
            break;
        }
        
        $this->load->view('default/roles/ajax_change_permission',array('role_id'=>$roleId,'permission_id'=>$permissionId,'status'=>$status));
    }
    */
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */